package net.jcip.chapter2;

import java.math.BigInteger;
import javax.servlet.*;

import net.jcip.annotations.*;

/**
 * UnsafeCountingFactorizer
 * <p>
 * Servlet that counts requests without the necessary synchronization
 * 在UnsafeCountingFactorizer中存在多个竞态条件，从而使结果变得不可靠。
 * 当某个计算的正确性取决于多个线程的交替执行时序时，那么就会发生竞态条件。
 *
 *
 * 我们想要统计下这个servlet 组件的点击率
 * @author Brian Goetz and Tim Peierls
 */
@NotThreadSafe
public class UnsafeCountingFactorizer extends GenericServlet implements Servlet {

    private long count = 0;  // 线程不安全

    public long getCount() {
        return count;
    }

    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        ++count;  //看上去是原子操作, 但是 在 CPU 执行中 是 包含了多个 操作
        encodeIntoResponse(resp, factors);
    }

    void encodeIntoResponse(ServletResponse res, BigInteger[] factors) {
    }

    BigInteger extractFromRequest(ServletRequest req) {
        return new BigInteger("7");
    }

    BigInteger[] factor(BigInteger i) {
        // Doesn't really factor
        return new BigInteger[]{i};
    }
}
